/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    angular.module('App.pages.member.entrust')
        .controller('NewEntrustCtrl', NewEntrustCtrl);

    function NewEntrustCtrl(entrustId,$scope,AppUtils,$state,Global,$location,$http,$timeout,LoginAccountAuth,EntrustService,$interval) {
        var vm = this;
        vm.entrust = {};
        vm.entrust.importantState = false;
        vm.entrustUseAudio = false;
        vm.audioMediaId = "";
        vm.localAudioId = "";
        vm.studentList = [];//家长绑定的孩子数字
        vm.chooseStudentList = [];//嘱托中选择的孩子
        vm.chooseStudentListTemp = [];
        vm.entrust.entrustType = 'text';
        vm.recordAuth = false;//是否授权录音
        vm.isEdit = false;//是否音频修改
        vm.isplaying = false;


        $scope.$on('$ionicView.enter', function(){
            var currentPath = $location.url();
            if(currentPath.indexOf("#") != -1){
                currentPath = currentPath.split('#')[0];
            }
            currentPath = Global.path.wechat_path + currentPath;
            $http.post(Global.path.server_sdk_auth_path,{"url":currentPath})
                .success(function(data){
                    wx.config({
                        debug: false,
                        appId: data.appId,
                        timestamp: data.timestamp,
                        nonceStr: data.noncestr,
                        signature: data.signature,
                        jsApiList: ['scanQRCode','startRecord','stopRecord','onVoiceRecordEnd','playVoice','pauseVoice','stopVoice','onVoicePlayEnd','uploadVoice']
                    });
                    wx.ready(function(){
                        wx.startRecord({
                            success: function(){
                                vm.recordAuth = true;
                                wx.stopRecord();
                            },
                            cancel: function () {
                                alert('用户拒绝授权录音');
                            }
                        });
                    });
                    wx.error(function(res){
                        alert(JSON.stringify(res));
                        console.log(res);
                    });
                })
                .error(function(data,header,config,status){
                    alert("请求微信sdk校验异常");
                });
        });




        var recordingTime,start,end;
        LoginAccountAuth.getAccount().then(function(data){
            angular.forEach(data.studentVoList,function(obj){
                if(!AppUtils.isUndefinedOrNull(obj.teacherId)){
                    vm.studentList.push(obj);
                }
            })
            vm.init();
        })

        //获取微信SDK授权
        vm.init = function(){
            //绑定播放按钮样式
            $(".play-button").on("click",function() {
                playAudio();
            });

            //页面初始化绑定事件
            $("#choose-child-btn,.entrust-create-screen").on("click",function(){
                $(".container").toggleClass('toggled');
            })
            $(".entrust-create-screen").on("click",".card-facebook",function(e){
                $(this).toggleClass('toggled');
                e.stopPropagation();
            })

            //往嘱托中添加宝宝
            $("#choose-student-btn").on("click",function(e){
                var keepGoing = true;
                var studentList = $(".entrust-create-screen").find(".card-facebook.toggled");
                studentList.each(function(){
                    var id = $(this).attr("data-studentId");
                    angular.forEach(vm.chooseStudentListTemp,function(data){
                        if(data.id === id){
                            keepGoing = false;
                            return;
                        }
                    })
                    if(keepGoing){
                        var obj = {};
                        obj.studentId = id;
                        obj.studentName = $(this).attr("data-studentName");
                        obj.studentAvatarPath = $(this).attr("data-studentAvatarPath");
                        obj.teacherName = $(this).attr("data-teacherName");
                        vm.chooseStudentListTemp.push(obj);
                    }
                    $(this).removeClass("toggled");
                })
                $scope.$apply(function () {
                    var obj = [];
                    var addToArray=true;
                    angular.forEach(vm.chooseStudentListTemp,function(a){
                        angular.forEach(vm.chooseStudentList,function(b){
                            if(b.studentId === a.studentId){
                                addToArray=false;
                                return;
                            }
                        })
                        if(addToArray){
                            vm.chooseStudentList.push(a);
                        }
                        addToArray=true;
                    })
                    vm.chooseStudentListTemp = [];
                    console.log(JSON.stringify(vm.chooseStudentList));
                });
            })

            //从嘱托中删除宝宝
            $scope.removeStudent = function(index){
                vm.chooseStudentList.splice(index, 1);
            }

            $('#record-btn').on('touchstart', function(event){
                event.preventDefault();
                if(vm.recordAuth){
                    $(".spinner").addClass("recording");
                    start = new Date().getTime();
                    var recordingTime = $timeout(function() {
                        wx.startRecord({
                            success: function(){
                            },
                            cancel: function () {
                                alert('用户拒绝授权录音');
                            }
                        });
                    },100);
                }else{
                    alert('获取录音权限失败，请稍后再试！');
                }
            });

            //松手结束录音
            $('#record-btn').on('touchend', function(event){
                event.preventDefault();
                $(".spinner").removeClass("recording");
                end = new Date().getTime();
                if((end - start) < 1500){
                    AppUtils.showTipsTop("录音太短啦，请重新录制!");
                    end = 0;
                    start = 0;
                    //小于300ms，不录音
                    clearTimeout(recordingTime);
                    wx.stopRecord();
                }else{
                    wx.stopRecord({
                        success: function (res) {
                            $("#audio-box").hide();
                            $(".record-play-div").show();
                            vm.localAudioId = res.localId;
                            playAudio();
                            wx.onVoicePlayEnd({
                                success: function (voicPlayEndRes) {
                                    pausedAudio();
                                }
                            });
                        },
                        fail: function (res) {
                            AppUtils.showAlert("微信录音失败" + JSON.stringify(res));
                        }
                    });
                }
            });

            if(!AppUtils.isUndefinedOrNull(entrustId)){
                EntrustService.loadEntrustInfo(entrustId).then(function(date){
                    if(!AppUtils.isUndefinedOrNull(date)){
                        vm.entrust = date;
                        if(vm.entrust.entrustType == "audio"){
                            vm.isEdit = true;
                            vm.entrustUseAudio = true;
                            vm.entrust.entrustType = 'audio';
                        }
                        if(vm.entrust.importantState == "true"){
                            vm.entrust.importantState = true;
                        }
                        angular.forEach(vm.studentList,function(obj){
                            if(obj.memberId == date.toEntrustChildId){
                                var student = {};
                                student.studentId = obj.memberId;
                                student.studentName = obj.memberName;
                                student.studentAvatarPath = obj.avatarPath;
                                student.teacherName = obj.teacherName;
                                vm.chooseStudentList.push(student);
                            }
                        })
                    }
                });
            }


            //播放音频开始动作
            function playAudio(){
                $(".play-button").removeClass("paused");
                $(".entrust-audio-play").addClass("playing");
                if(!vm.isplaying){
                    if(!AppUtils.isUndefinedOrNull(vm.localAudioId)){
                        wx.playVoice({
                            localId: vm.localAudioId // 需要播放的音频的本地ID，由stopRecord接口获得
                        });
                    }else{
                        if(vm.isEdit){
                            var audio = $("audio")[0];
                            var interval;
                            var nprogress = $(".audio-nprogress")[0];
                            if(!AppUtils.isUndefinedOrNull(audio)){
                                audio.addEventListener("playing", function() {
                                    vm.isplaying = true;
                                    var duration = Math.ceil(audio.duration*500);//总毫秒数
                                    var count = duration/50;
                                    var i = 100/count * 1000;
                                    var s = 0;
                                    interval = $interval(function(){
                                        s = s + i;
                                        nprogress.style.width =  s/1000 + "%";
                                    }, 50, count);
                                }, false);
                                //音频可以播放完毕
                                audio.addEventListener("ended", function() {
                                    vm.isplaying = false;
                                    $timeout(function(){
                                        pausedAudio();
                                        nprogress.style.width = "0%";
                                        $interval.cancel(interval);
                                    },200)
                                }, false);
                                audio.play();
                            }
                        }
                    }
                }


            }
            //播放音频完成动作
            function pausedAudio(){
                $(".play-button").addClass("paused");
                $(".entrust-audio-play").removeClass("playing");
            }


        }

        $scope.removeAudio = function(){
            $("#audio-box").show();
            $(".record-play-div").hide();
        }

        $scope.$on('$ionicView.beforeLeave', function(){
            wx.stopRecord();
        });

        //保存嘱托
        $scope.submitEntrust = function(){
            var obj = {};
            var studentList = [];
            angular.forEach(vm.chooseStudentList,function(data){
                studentList.push(data.studentId);
            })

            if(studentList.length < 1){
                AppUtils.showTipsTop("请选择宝宝！");
                return;
            }
            if(!AppUtils.isUndefinedOrNull(entrustId)){
                obj = _.clone(vm.entrust);
            }
            obj.studentIds = _.clone(studentList);
            obj.importantState = vm.entrust.importantState;

            if(vm.entrustUseAudio){
                if(AppUtils.isUndefinedOrNull(vm.localAudioId)){
                    AppUtils.showTipsTop("请按住麦克风录入嘱托！");
                    return;
                }
                var recordConfirm = AppUtils.showConfirm("确认上传录音吗？");
                recordConfirm.then(function(result) {
                    if(result) {
                        wx.uploadVoice({
                            localId: vm.localAudioId, // 需要上传的音频的本地ID，由stopRecord接口获得
                            isShowProgressTips: 1, // 默认为1，显示进度提示
                            success: function (uploadVoiceRes) {
                                obj.entrustType = 'audio';
                                obj.mediaId = uploadVoiceRes.serverId;
                                EntrustService.createEntrust(obj);
                            }
                        });
                    }
                });
            }else{
                if(AppUtils.isUndefinedOrNull(vm.entrust.entrustContent)){
                    AppUtils.showTipsTop("请输入嘱托内容！");
                    return;
                }
                obj.entrustType = 'text';
                obj.entrustContent = vm.entrust.entrustContent;
                EntrustService.createEntrust(obj);
            }
        }
    }

})();